#include "client.hpp"
#include <cstdio>
#include <sys/select.h>
Zhuce login_msg;
time_t now;
int main(int argc, char *argv[])
{
    int clientfd = tcpConnect("127.0.0.1", 8080);
    userLogin(clientfd);
    char buf[128] = {0};
    fd_set rdset;
    train_t t;
    while (true)
    {
        FD_ZERO(&rdset);
        FD_SET(clientfd, &rdset);
        FD_SET(STDIN_FILENO, &rdset);
        int ready = select(clientfd + 1, &rdset, nullptr, nullptr, nullptr);
        printf("ready : %d \n", ready);
        if (FD_ISSET(STDIN_FILENO, &rdset))
        {
            memset(buf, 0, sizeof(buf));
            int ret = read(STDIN_FILENO, buf, sizeof(buf));
            if (0 == ret)
            {
                printf("byebye.\n");
                break;
            }
            memset(&t, 0, sizeof(t));
            buf[strlen(buf) - 1] = '\0';
            parseCommand(buf, strlen(buf), &t);
            sendn(clientfd, &t, 4 + 4 + t.len);
            if (t.type == CMD_TYPE_PUTS)
            {
                putsCommand(clientfd, &t);
            }
        }
        else if (FD_ISSET(clientfd, &rdset))
        {
            // recv(clientfd, buf, sizeof(buf), 0);
            // printf("recv: %s\n", buf);
            int length = -1;
            int ret = recvn(clientfd, &length, sizeof(length));
            int cmdType = -1;
            ret = recvn(clientfd, &cmdType, sizeof(cmdType));
            if (cmdType == CMD_TYPE_LS)
            {
                char ls_ret[4096] = {0};
                recvn(clientfd, ls_ret, length);
                printf("%s\n", ls_ret);
            }
        }
    }
    close(clientfd);
    return 0;
}